package com.uraurora.crescent.ai.bt

import com.uraurora.crescent.ai.bt.BTStatus.*
import java.util.*

class Dog @JvmOverloads constructor(var name: String, btree: BehaviourTree<Dog>? = null) {
    var brainLog: String
    private var behaviorTree: BehaviourTree<Dog>?
    fun getBehaviorTree(): BehaviourTree<Dog>? {
        return behaviorTree
    }

    fun setBehaviorTree(behaviorTree: BehaviourTree<Dog>?) {
        this.behaviorTree = behaviorTree
    }

    fun bark() {
        if (Random().nextBoolean()) log("Arf arf") else log("Woof")
    }

    fun startWalking() {
        log("Let's find a nice tree")
    }

    fun randomlyWalk() {
        log("SNIFF SNIFF - Dog walks randomly around!")
    }

    fun stopWalking() {
        log("This tree smells good :)")
    }

    fun markATree(i: Int): Boolean? {
        if (i == 0) {
            log("Swoosh....")
            return null
        }
        if (Random().nextBoolean()) {
            log("MUMBLE MUMBLE - Still leaking out")
            return java.lang.Boolean.FALSE
        }
        log("I'm ok now :)")
        return java.lang.Boolean.TRUE
    }

    fun log(msg: String?) {
        println("name=$name, msg=$msg")
    }

    fun brainLog(msg: String?) {
        println("brainLog=$brainLog, msg=$msg")
    }

    init {
        brainLog = "$name brain"
        behaviorTree = btree
        btree?.setObject(this)
    }
}

class Bark(val times: Int) : LeafNode<Dog?>() {
    override fun execute(): BTStatus {
        for (i in 0 until times) {
            `object`?.bark()
        }
        return SUCCEEDED
    }
}

class Mark(var index: Int) : LeafNode<Dog>(){

    override fun start() {
        super.start()
        `object`?.log("Dog lifts a leg and pee!")
    }

    override fun execute(): BTStatus {
        val result = `object`?.markATree(index++) ?: return RUNNING
        return if (result) SUCCEEDED else FAILED
    }
}

class Play : LeafNode<Dog?>() {
    override fun start() {
        `object`?.brainLog("WOW - Lets play!")
    }

    override fun execute(): BTStatus {
        `object`?.brainLog("PANT PANT - So fun")
        return RUNNING
    }

    override fun end() {
        `object`?.brainLog("SIC - No time to play :(")
    }
}

class RestTask : LeafNode<Dog?>() {
    override fun start() {
        `object`?.brainLog("YAWN - So tired...")
    }

    override fun execute(): BTStatus {
        `object`?.brainLog("zz zz zz")
        return RUNNING
    }

    override fun end() {
        `object`?.brainLog("SOB - Time to wake up")
    }
}